import { apiPrefix } from '@/common/config';
import { message } from '@aurum/pfe-ui';
import { getToken, removeToken } from '@mcd/boss-common/dist/utils/auth';
import axios from 'axios';

const instance = axios.create({
  baseURL: apiPrefix,
  timeout: 1000 * 60, // 延迟时间(ms)
  withCredentials: true,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
});

let sysValues = ['syslang', 'sysdictionary', 'sysparams'];
instance.interceptors.request.use(
  (config) => {
    const _token = getToken();
    if (_token) {
      config.headers['Authorization'] = _token;
      config.headers['Cache-Control'] = 'no-cache';
    }
    const signs = localStorage.getItem('sign');

    if (signs) {
      config.headers['appkey'] = 'platform';
      config.headers['sign'] = signs;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (response.headers) {
      if (parseInt(res.code) === 2010) {
        return;
      }
      for (let i in response.headers) {
        // eslint-disable-next-line no-prototype-builtins
        if (response.headers.hasOwnProperty(i) && sysValues.includes(i)) {
          localStorage.setItem(i, response.headers[i]);
        }
      }
    }
    if (response?.config?.getResponse) {
      return response;
    }
    if (parseInt(res.code) === 4030) {
      removeToken();
      message.warning('登录过期！');
      setTimeout(() => {
        window.location.href = window.location.origin + '/login';
      }, 1000);
      return Promise.reject(res);
    } else if (parseInt(res.code) === 4050) {
      message.warning(res.message || '没有权限！');
      return Promise.reject(res);
    } else if ([2000].includes(parseInt(res.code))) {
      if (response?.config?.onlyData) {
        return Promise.resolve(response.data.data);
      }
      return Promise.resolve(response.data);
    } else {
      message.warning(res.errMsg || '系统异常！');
      return Promise.reject(res);
    }
  },
  (error) => {
    // ignore canceled
    if (error && error.code === 'ERR_CANCELED') return;

    let errStr = error.toString();
    if (error.toString() !== 'Cancel' && !errStr.includes('timeout of')) {
      message.warning(error.message || '系统异常！');
      return Promise.reject(error);
    }
    if (errStr.includes('timeout of')) {
      message.warning('请求超时');
      return Promise.reject(error);
    }
  }
);

export default instance;
